import "package:ducafe_ui_core/ducafe_ui_core.dart";
import "package:flutter/material.dart";
import 'dart:math' as math;
import "package:flutter_mobx/flutter_mobx.dart";
import "package:go_router/go_router.dart";
import "package:hinge/common/index.dart";
import "package:hinge/store/index.dart";

// 半圆形裁剪器
class HalfCircleClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();
    path.moveTo(0, size.height / 2);
    path.arcToPoint(
      Offset(0, size.height / 2),
      radius: Radius.elliptical(size.width / 2, size.height / 2),
      clockwise: true,
    );
    path.close();
    return path;
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}

// 环形进度绘制器 - 全新实现
class CircularProgressPainter extends CustomPainter {
  final double percentage;
  final Color progressColor;
  final double strokeWidth;

  CircularProgressPainter({
    required this.percentage,
    required this.progressColor,
    required this.strokeWidth,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final double width = size.width;
    final double height = size.height;
    final double radius = height / 2;
    final Offset center = Offset(0, height / 2); // 中心在左边缘中央

    // 紫色半圆背景
    final Paint backgroundPaint =
        Paint()
          ..color = Color(0xFFE7D3FF)
          ..style = PaintingStyle.fill;

    // 绘制半圆背景 (半圆向右)
    canvas.drawArc(
      Rect.fromCenter(center: center, width: radius * 2, height: height),
      -math.pi / 2, // 从顶部开始
      math.pi, // 180度
      true, // 使用中心点连接
      backgroundPaint,
    );

    // 计算进度线的角度 (0-100% 对应 0-180度)
    final double startAngle = math.pi / 2; // 从底部开始 (90度)
    final double sweepAngle = -math.pi * percentage / 100; // 逆时针向上，负号表示逆时针

    // 白色进度线
    final Paint progressPaint =
        Paint()
          ..color = progressColor
          ..style = PaintingStyle.stroke
          ..strokeWidth = strokeWidth
          ..strokeCap = StrokeCap.round;

    // 画进度线
    canvas.drawArc(
      Rect.fromCenter(
        center: center,
        width: radius * 2 - strokeWidth, // 稍微缩小一点，避免被裁剪
        height: height - strokeWidth,
      ),
      startAngle, // 从底部开始
      sweepAngle, // 进度角度，负值表示逆时针
      false, // 不使用中心点连接
      progressPaint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

class MessagePage extends StatefulWidget {
  const MessagePage({super.key});

  @override
  State<MessagePage> createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> with RouteAware {
  final _rootStore = RootStore();
  final PageController _pageController = PageController(viewportFraction: 1.0);
  int _currentPageIndex = 0;
  double _currentPageValue = 0.0;

  // 讨论话题列表
  final List<Map<String, dynamic>> _discussionTopics = [
    {
      'title': 'Woody Fragrances',
      'image': AssetsImages.group1,
      'description': 'Deep, earthy scents with hints of sandalwood and cedar',
      'chatId': 'group1',
    },
    {
      'title': 'Floral Bouquets',
      'image': AssetsImages.group2,
      'description':
          'Elegant compositions with jasmine, rose, and violet notes',
      'chatId': 'group2',
    },
    {
      'title': 'Fresh Citrus',
      'image': AssetsImages.group3,
      'description': 'Energizing scents with lemon, bergamot, and mandarin',
      'chatId': 'group3',
    },
  ];

  @override
  void initState() {
    super.initState();
    _rootStore.messageStore.loadMessages();
    _rootStore.messageStore.loadTopics();

    // 添加页面更改监听器
    _pageController.addListener(() {
      setState(() {
        _currentPageValue = _pageController.page!;
        if (_pageController.page!.round() != _currentPageIndex) {
          _currentPageIndex = _pageController.page!.round();
        }
      });
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 注册路由观察者
    AppRouter.routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  @override
  void dispose() {
    AppRouter.routeObserver.unsubscribe(this);
    _pageController.dispose();
    super.dispose();
  }

  // 当页面重新获得焦点时调用
  @override
  void didPopNext() {
    // 从其他页面返回时，重新加载话题数据
    _rootStore.messageStore.loadTopics();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment(0.50, -0.00),
            end: Alignment(0.50, 1.00),
            colors: [const Color(0xFFA794FD), const Color(0xFFFFEFFA)],
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Column(
              children: [
                SizedBox(height: 20.h),

                // Text(
                //   'Hot Discussions',
                //   style: TextStyle(
                //     color: Colors.white,
                //     fontSize: 22.sp,
                //     fontWeight: FontWeight.w700,
                //   ),
                // ).alignLeft(),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'Hot Discussions',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 22.sp,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                    // 添加聊天入口按钮
                    GestureDetector(
                      onTap: () {
                        // 检查用户是否登录
                        final currentUser = UserService.getCurrentUser();
                        if (currentUser == null || UserService.isGuestUser()) {
                          // 显示登录提示对话框
                          CustomDialog.show(
                            context: context,
                            title: 'Login Required',
                            content:
                                'You need to login to view your messages. Would you like to login now?',
                            cancelText: 'Cancel',
                            confirmText: 'Login',
                            onConfirm: () {
                              context.push('/login');
                            },
                          );
                        } else {
                          // 用户已登录，跳转到聊天列表页面
                          context.push('/chats');
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.all(8.w),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.3),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          IconFont.message,
                          color: Colors.white,
                          size: 24.w,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 20.h),

                // 上方横向滚动区域 - 3个项目，带有放大缩小动画
                SizedBox(
                  height: 241.h,
                  child: Column(
                    children: [
                      Expanded(
                        child: PageView.builder(
                          controller: _pageController,
                          itemCount: _discussionTopics.length,
                          onPageChanged: (index) {
                            setState(() {
                              _currentPageIndex = index;
                            });
                          },
                          itemBuilder: (context, index) {
                            // 计算缩放因子
                            double scale = 1.0;
                            if (_pageController.position.haveDimensions) {
                              // 当前项与显示项之间的距离
                              double diff = (index - _currentPageValue).abs();
                              // 限制差值在0到1之间
                              diff = diff.clamp(0.0, 1.0);
                              // 计算缩放，当前项为1.0，其他项为0.85
                              scale = 1.0 - (0.15 * diff);
                            }

                            final topic = _discussionTopics[index];
                            return _buildTopicCard(topic, scale);
                          },
                        ),
                      ),

                      // 分段式指示器
                      Padding(
                        padding: EdgeInsets.only(top: 15.h, bottom: 10.h),
                        child: _buildSegmentedIndicator(
                          itemCount: _discussionTopics.length,
                          currentIndex: _currentPageIndex,
                        ),
                      ),
                    ],
                  ),
                ),

                // 标题
                Text(
                  'Classic Perfume FAQ',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 22.sp,
                    fontWeight: FontWeight.w700,
                  ),
                ).alignLeft(),

                // 下方问题列表
                Expanded(
                  child: Observer(
                    builder: (_) {
                      final topics = _rootStore.messageStore.topics;

                      return ListView.builder(
                        padding: EdgeInsets.only(top: 6.h, bottom: 120.h),
                        itemCount: topics.length,
                        itemBuilder: (context, index) {
                          final topic = topics[index];
                          return Align(
                            alignment: Alignment.center,
                            child: _buildMessageItem(topic),
                          );
                        },
                      );
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 构建话题卡片，带有缩放动画
  Widget _buildTopicCard(Map<String, dynamic> topic, double scale) {
    // 获取对应的群聊ID
    String? groupKey;
    if (topic['title'] == 'Woody Fragrances') {
      groupKey = 'woody';
    } else if (topic['title'] == 'Floral Bouquets') {
      groupKey = 'floral';
    } else if (topic['title'] == 'Fresh Citrus') {
      groupKey = 'citrus';
    }

    return Transform(
      transform: Matrix4.identity()..scale(scale, scale),
      alignment: Alignment.center,
      child: Container(
        width: 374.w,
        height: 241.h,
        padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 22.h),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(topic['image']),
            fit: BoxFit.fill,
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              topic['title'],
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 23.h),
            SizedBox(
              width: 175.w,
              height: 60.h,
              child: Text(
                topic['description'],
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400,
                  color: Colors.white,
                ),
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Spacer(),
            // 加入按钮
            GestureDetector(
              onTap: () {
                _handleJoinGroupChat(topic['chatId']);
              },
              child: Container(
                width: 129.w,
                height: 50.h,
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(AssetsImages.join),
                    fit: BoxFit.fill,
                  ),
                ),
              ),
            ).alignLeft(),
            SizedBox(height: 18.h),
          ],
        ),
      ),
    );
  }

  // 显示登录提示对话框
  void _showLoginRequiredDialog(String groupKey) {
    CustomDialog.show(
      context: context,
      title: 'Login Required',
      content:
          'You need to login to join this chat group. Would you like to login now?',
      cancelText: 'Cancel',
      confirmText: 'Login',
      onConfirm: () {
        context.push('/login');
      },
    );
  }

  // 处理加入群聊按钮点击
  // 处理加入群聊按钮点击
  void _handleJoinGroupChat(String? chatId) async {
    if (chatId == null) return;

    // 检查用户是否登录
    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      // 显示登录提示对话框
      _showLoginRequiredDialog(chatId);
      return;
    }

    // 检查用户是否已在群聊中
    bool isInChat = await ChatService.isUserInChat(chatId, currentUser.id);

    if (!isInChat) {
      // 用户不在群聊中，添加用户到群聊
      bool success = await ChatService.addUserToChat(chatId, currentUser.id);
      if (!success) {
        // 添加失败，可以显示错误提示
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to join the chat group')),
        );
        return;
      }
    }

    // 无论是已在群聊中还是刚加入群聊，都导航到聊天页面
    _navigateToChatPage(chatId);
  }

  // 导航到群聊页面
  void _navigateToChatPage(String chatId) {
    // 直接跳转到聊天页面
    context.push('/chat/$chatId');
  }

  // 话题列表项
  Widget _buildMessageItem(TopicModel topic) {
    final percentage = topic.percentage;

    return Container(
      width: 374.w,
      height: 96.h,
      margin: EdgeInsets.symmetric(vertical: 8.h),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment(0.00, 0.50),
          end: Alignment(1.00, 0.50),
          colors: [const Color(0xFFDFC4FF), const Color(0xFFFBEBFF)],
        ),
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 8,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(12.r),
        onTap: () {
          // 点击跳转到话题详情页
          context.push('/topic/${topic.id}');
        },
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 左侧半圆和百分比
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(12.r),
                bottomLeft: Radius.circular(12.r),
              ),
              child: SizedBox(
                width: 48.h, // 宽度为高度的一半
                height: 96.h,
                child: Stack(
                  children: [
                    // 半圆背景和进度条
                    Positioned.fill(
                      child: CustomPaint(
                        painter: CircularProgressPainter(
                          percentage: percentage,
                          progressColor: Colors.white,
                          strokeWidth: 3.0, // 进度条宽度
                        ),
                      ),
                    ),

                    // 百分比文字 - 放在半圆中间位置
                    Positioned(
                      left: 8.w,
                      top: 0,
                      bottom: 0,
                      child: Center(
                        child: Text(
                          '${percentage.toInt()}%',
                          style: TextStyle(
                            fontSize: 18.sp,
                            fontWeight: FontWeight.w500,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // 右侧问题文本
            Expanded(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                child: Text(
                  topic.question,
                  style: TextStyle(
                    color: Color(0xFF150555),
                    fontSize: 16.sp,
                    fontFamily: 'Inter',
                    fontWeight: FontWeight.w400,
                  ),
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),

            // 右侧聊天图标
            Padding(
              padding: EdgeInsets.only(right: 16.w),
              child: Icon(
                IconFont.message,
                color: Color(0xFF9981B7),
                size: 24.w,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 分段式指示器
  Widget _buildSegmentedIndicator({
    required int itemCount,
    required int currentIndex,
  }) {
    // 固定长条长度
    final double indicatorWidth = 100.w;
    // 计算每段宽度
    final double segmentWidth = indicatorWidth / itemCount;

    return SizedBox(
      width: indicatorWidth,
      height: 4.h,
      child: Stack(
        children: [
          // 背景长条 - 浅色
          Container(
            width: indicatorWidth,
            height: 4.h,
            decoration: BoxDecoration(
              color: Colors.black.withValues(alpha: 0.15),
              borderRadius: BorderRadius.circular(2.r),
            ),
          ),

          // 前景指示器 - 深色，随当前页面位置移动
          AnimatedPositioned(
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
            left: currentIndex * segmentWidth,
            child: Container(
              width: segmentWidth,
              height: 4.h,
              decoration: BoxDecoration(
                color: Color(0xFF150555),
                borderRadius: BorderRadius.circular(2.r),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
